import 'dart:async';

/// 厦门大学计算机专业 | 前华为工程师
/// 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
/// 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
/// 公众号：蓝不蓝编程
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(HspApp());

class HspApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      // theme: new ThemeData(
      //   brightness: Brightness.dark,
      // ),
      home: HspPage(),
    );
  }
}

class HspPage extends StatefulWidget {
  const HspPage({Key? key}) : super(key: key);

  @override
  _HspPageState createState() => _HspPageState();
}

class _HspPageState extends State<HspPage> {
  final interval = const Duration(milliseconds: 100);
  var timeText = "00:00:00.000";
  var swatch = Stopwatch();
  var timer;

  void startTimer() {
    swatch.start();
    timer = Timer.periodic(interval, (timer) {
      changeText();
    });
  }

  void pauseTimer() {
    timer.cancel();
    swatch.stop();
  }

  void resetTimer() {
    timer.cancel();
    swatch.reset();
    setState(() {
      timeText = "00:00:00.000";
    });
  }

  void changeText() {
    setState(() {
      timeText = swatch.elapsed.inHours.toString().padLeft(2, "0") +
          ":" +
          (swatch.elapsed.inMinutes % 60).toString().padLeft(2, "0") +
          ":" +
          (swatch.elapsed.inSeconds % 60).toString().padLeft(2, "0") +
          "." +
          (swatch.elapsed.inMilliseconds % 1000).toString().padLeft(3, "0");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("秒表-蓝不蓝编程"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            timeText,
            style: const TextStyle(fontSize: 30),
          ),
          const Padding(padding: EdgeInsets.all(40)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              FloatingActionButton(
                child: const Icon(Icons.play_arrow, color: Colors.white, size: 40),
                backgroundColor: Colors.green,
                onPressed: startTimer,
              ),
              FloatingActionButton(
                child: const Icon(Icons.pause, color: Colors.white, size: 40),
                backgroundColor: Colors.yellow,
                onPressed: pauseTimer,
              ),
              FloatingActionButton(
                child: const Icon(
                  Icons.refresh,
                  color: Colors.white,
                  size: 40,
                ),
                backgroundColor: Colors.red,
                onPressed: resetTimer,
              )
            ],
          )
        ],
      ),
    );
  }
}
